package cn.train.controler;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.train.model.Query;
import cn.train.service.QueryTrainService;
import cn.train.util.Pageutil;
@WebServlet("/QueryBykeywordServlet")
public class QueryBykeywordServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//模糊查询
		
		String flag=request.getParameter("flag");
		
		
		
		HttpSession session = request.getSession();
		String currPage = request.getParameter("pageIndex");
		String gname=request.getParameter("goname");
     	String shijian=request.getParameter("shijian");
     	  
     	
     	if(!"".equals(shijian)&&!"".equals(gname)&&shijian!=null&&gname!=null){
     		session.setAttribute("gname", gname);
     		session.setAttribute("shijian", shijian);
     		
     	}
     	
     	gname=(String)session.getAttribute("gname");
		shijian=(String)session.getAttribute("shijian");
		SimpleDateFormat adf = new SimpleDateFormat("yyyy-MM-dd");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out=response.getWriter();
		if (currPage == null) {
			currPage = "1";
		}
		int pageIndex = Integer.parseInt(currPage);
		QueryTrainService qts=new QueryTrainService();
		try {
			 Date date = adf.parse(shijian);
			java.sql.Date sqlDate=new java.sql.Date(date.getTime());
			// 总条数
			int count = qts.getCount1(gname,sqlDate);
			Pageutil pu = new Pageutil();
			// 总页数
			int totalPage = pu.getTotalPage(count,5);
			if(pageIndex<1){
				pageIndex=1;
			}else if(pageIndex>totalPage){
				pageIndex=totalPage;
			}
			//分页查询主代码结束
			List<Query> querys=qts.QueryByKeyword(gname, sqlDate,pageIndex,5);
			if(querys.size()==0){
				out.print("<script>alert('您选择的信息有误，请重新选择！');location.href='QueryTrainServlet'</script>;");}
			else{
			request.setAttribute("list2",querys);
			request.setAttribute("pageIndex", pageIndex);
			request.setAttribute("totalPage", totalPage);
			request.getRequestDispatcher("back/admin/searchTrain.jsp").forward( request,response);
		}}
		catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
		
	
	}
   @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
     doGet(req, resp);
   }
}
